<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会员名称" prop="memberUuid">
        <el-input
          v-model="queryParams.memberUuid"
          placeholder="请输入会员名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会员昵称" prop="memberName">
        <el-input
          v-model="queryParams.memberName"
          placeholder="请输入会员昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="记录更新时间" prop="updatedAt">
        <el-date-picker clearable
          v-model="queryParams.updatedAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择记录更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['huiyuan:member:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Edit"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['huiyuan:member:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['huiyuan:member:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['huiyuan:member:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="memberId" />
      <el-table-column label="会员名称" align="center" prop="memberUuid" />
      <el-table-column label="会员昵称" align="center" prop="memberName" />
      <el-table-column label="联系方式" align="center" prop="contact" />
      <el-table-column label="积分数量" align="center" prop="points" />
      <el-table-column label="上次登录时间" align="center" prop="lastLoginTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastLoginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录更新时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button 
            v-if="scope.row.isEnabled === 0" 
            link 
            type="success" 
            icon="Check" 
            @click="handleEnable(scope.row)"
          >启用</el-button>
          <el-button 
            v-if="scope.row.isEnabled === 1" 
            link 
            type="warning" 
            icon="Close" 
            @click="handleDisable(scope.row)"
          >禁用</el-button>
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['huiyuan:member:edit']">修改</el-button>-->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['huiyuan:member:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员列表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="memberRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会员名" prop="memberName">
          <el-input v-model="form.memberName" placeholder="请输入会员名" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登录密码" />
        </el-form-item>
        <el-form-item label="用户头像URL" prop="avatarUrl">
          <image-upload v-model="form.avatarUrl"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="积分数量" prop="points">
          <el-input v-model="form.points" placeholder="请输入积分数量" />
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker clearable
            v-model="form.birthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择生日">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="地区" prop="region">
          <el-input v-model="form.region" placeholder="请输入地区" />
        </el-form-item>
        <el-form-item label="记录创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择记录创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="记录更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择记录更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Member">
import { listMember, getMember, delMember, addMember, updateMember } from "@/api/huiyuan/member"
import { useRouter } from 'vue-router'
import { onActivated } from 'vue'
const router = useRouter();

const { proxy } = getCurrentInstance()

const memberList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    memberUuid: null,
    memberName: null,
    contact: null,
    updatedAt: null
  },
  rules: {
    memberUuid: [
      { required: true, message: "UUID唯一标识不能为空", trigger: "blur" }
    ],
    memberName: [
      { required: true, message: "会员名不能为空", trigger: "blur" }
    ],
    password: [
      { required: true, message: "登录密码不能为空", trigger: "blur" }
    ],
    registerTime: [
      { required: true, message: "注册时间不能为空", trigger: "blur" }
    ],
    roleId: [
      { required: true, message: "角色标识不能为空", trigger: "change" }
    ],
    createdAt: [
      { required: true, message: "记录创建时间不能为空", trigger: "blur" }
    ],
    updatedAt: [
      { required: true, message: "记录更新时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询会员列表列表 */
function getList() {
  loading.value = true
  listMember(queryParams.value).then(response => {
    memberList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    memberId: null,
    memberUuid: null,
    memberName: null,
    password: null,
    avatarUrl: null,
    contact: null,
    registerTime: null,
    points: null,
    roleId: null,
    gender: null,
    birthday: null,
    region: null,
    lastLoginTime: null,
    isEnabled: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("memberRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.memberId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加会员列表"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _memberId = row.memberId || ids.value
  getMember(_memberId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改会员列表"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["memberRef"].validate(valid => {
    if (valid) {
      if (form.value.memberId != null) {
        updateMember(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMember(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _memberIds = row.memberId || ids.value
  proxy.$modal.confirm('是否确认删除会员列表编号为"' + _memberIds + '"的数据项？').then(function() {
    return delMember(_memberIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('huiyuan/member/export', {
    ...queryParams.value
  }, `member_${new Date().getTime()}.xlsx`)
}

getList()

onActivated(() => {
  getList()
})

function handleStatusChange(row) {
  console.log(row,"状态更改")
  let text = row.isEnabled === 1 ? "启用" : "禁用";
  proxy.$modal.confirm(`确认要\"${text}\"会员 \"${row.memberName}\" 吗？`).then(() => {
    return updateMember({ ...row });
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(() => {
    row.isEnabled = row.isEnabled === 1 ? 0 : 1;
  });
}

function handleView(row) {
  // 直接使用路由跳转
  router.push({ 
    path: '/huiyuan/jibenxinxi', 
    query: { memberId: row.memberId } 
  });
}

function handleEnable(row) {
  proxy.$modal.confirm(`确认要启用会员 "${row.memberName}" 吗？`).then(() => {
    return updateMember({ ...row, isEnabled: 1 });
  }).then(() => {
    proxy.$modal.msgSuccess("启用成功");
    getList();
  }).catch(() => {});
}

function handleDisable(row) {
  proxy.$modal.confirm(`确认要禁用会员 "${row.memberName}" 吗？`).then(() => {
    return updateMember({ ...row, isEnabled: 0 });
  }).then(() => {
    proxy.$modal.msgSuccess("禁用成功");
    getList();
  }).catch(() => {});
}
</script>
